<template>
  <div v-if="isLoading" style="text-align: center; margin-top: 20px">
    {{ $t("shoppingcart.loadingMessage") }}
  </div>
  <div v-else>
    <div style="margin-top: 2px; margin-bottom: 5px">
      <div class="search-container">
        <el-checkbox
          v-model="data.checkAll"
          @change="handleCheckAll"
          style="margin-right: 10px"
          >{{ $t("selectAll.checkAllBoxText") }}</el-checkbox
        >
        <el-input
          style="width: 400px; margin-right: 10px"
          size="medium"
          v-model="data.name"
          :placeholder="$t('search.inputPlaceholder')"
          prefix-icon="Search"
          clearable
        >
          <template #prepend>
            <!-- 分类选择框 -->
            <el-select
              v-model="data.select"
              :placeholder="$t('search.categoryPlaceholder')"
              style="width: 100px"
              size="large"
              @change="load"
            >
              <!-- 避免空数组调用filter，确保categories有数据再渲染 -->
              <el-option-group
                v-for="category in (data.categories || []).filter(
                  (c) => c.parentId === null
                )"
                :key="category.id"
                :label="category.name"
              >
                <!-- 二级分类选项，过滤出该一级分类的子分类 -->
                <el-option
                  v-for="subCategory in (data.categories || []).filter(
                    (c) => c.parentId === category.id
                  )"
                  :key="subCategory.id"
                  :label="subCategory.name"
                  :value="subCategory.id"
                />
              </el-option-group>
            </el-select>
          </template>
        </el-input>

        <el-button type="primary" @click="search">{{
          $t("search.buttonText")
        }}</el-button>
        <el-button
          type="primary"
          @click="batchOrder"
          :disabled="selectedCartIds.length === 0"
          >{{ $t("shoppingcart.batchOrderButtonText") }}</el-button
        >
        <el-button
          type="primary"
          @click="batchCollect"
          :disabled="selectedCartIds.length === 0"
          >{{ $t("shoppingcart.batchCollectButtonText") }}</el-button
        >
        <el-button
          type="danger"
          @click="batchDelete"
          :disabled="selectedCartIds.length === 0"
          >{{ $t("selectAll.batchDeleteButtonText") }}</el-button
        >
      </div>

      <section class="recommended-product">
        <div
          v-for="product in shoppingCart.products"
          :key="product.id"
          class="product-item"
        >
          <el-checkbox
            v-model="product.checked"
            @change="updateSelectedCartIds"
            style="margin-right: 10px"
          ></el-checkbox>
          <img
            :src="getProductImage(product)"
            alt="Product Image"
            class="product-image"
          />
          <div class="ShoppingCart-product-info">
            <h2 class="product-name" :title="product.productName">
              {{ product.productName }}
            </h2>
            <div style="margin: 10px 0; align-items: center">
              <div style="margin-right: 10px">
                <p style="color: #919090">
                  {{ $t("shoppingcart.unitPriceText") }}￥{{
                    product.unitPrice
                  }}
                </p>
                <el-input-number
                  v-model="product.quantity"
                  :min="1"
                  @change="calculateTotalPrice(product)"
                  style="width: 100px"
                ></el-input-number>
                <strong
                  style="color: #ec6117; font-size: 18px; margin-left: 20px"
                  >{{ $t("shoppingcart.totalPriceText") }}￥{{
                    product.totalPrice
                  }}</strong
                >
              </div>
              <div>
                <div style="text-align: right">
                  <el-button
                    type="success"
                    @click="deleteSingleProduct(product.id)"
                    >{{ $t("selectAll.deleteButtonText") }}</el-button
                  >
                  <el-button
                    type="primary"
                    @click="placeOrder(product)"
                    :disabled="product.quantity <= 0"
                    >{{ $t("shoppingcart.buyButtonText") }}</el-button
                  >
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="data.pageNum"
            v-model:page-size="data.pageSize"
            :page-sizes="[5, 10, 15, 20]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="data.total"
          />
        </div>
      </section>
    </div>
  </div>
</template>

<script setup>
import "../../assets/css/ShoppingCart.css";
import { reactive, onMounted, ref } from "vue";
import router from "@/router/index.js";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";

//获取当前用户信息
const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerid = userInfo.id;
console.log("用户ID为：", buyerid);
console.log("用户id类型为：", typeof buyerid);
const isLoading = ref(true);

const data = reactive({
  name: null,
  pageNum: 1,
  pageSize: 10,
  total: 13,
  productList: [],
  checkAll: false,
  select: null,
  categories: [], //分类数据
});

const adressId = ref(1);

//获取分类数据
const loadCategories = () => {
  request
    .get("/Category/selectAll")
    .then((res) => {
      if (res.msg === "成功") {
        data.categories = res.data; // 设置分类数据
      } else {
        ElMessage({
          message: $t("shoppingcart.getCategoriesErrorMessage"),
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("获取分类数据失败", err);
      ElMessage({
        message: $t("shoppingcart.getCategoriesRetryMessage"),
        type: "error",
      });
    });
};

const shoppingCart = reactive({
  shoppingCartId: "",
  productId: "",
  buyer_id: buyerid,
  //product_id:'',
  products: [], //用于存储购物车商品
});

// 保存已选商品
const selectedCartIds = reactive([]);

//获取用户购物车商品
const getUserCartItems = () => {
  request
    .get(`ShoppingCart/selectShCartById/${buyerid}`)
    .then((res) => {
      if (res.data) {
        console.log("后端返回的购物车商品数据:", res.data); // 打印后端返回的数据
        shoppingCart.products = res.data; //保存商品列表
        shoppingCart.products.forEach((product) => {
          product.checked = false; //默认未选中
          // product.quantity = product.quantity || 1; // 默认商品数量为 1
          calculateTotalPrice(product); // 初始化总价
        });
        console.log("赋值后：", shoppingCart.products);
      } else {
        shoppingCart.products = [];
        ElMessage({
          message: $t("shoppingcart.noProductsMessage"),
          type: "warning",
        });
      }
      isLoading.value = false; // 数据加载完成，隐藏加载提示
    })
    .catch((error) => {
      console.error("获取购物车商品失败：", error);
      ElMessage({
        message: $t("shoppingcart.getCartItemsErrorMessage"),
        type: "error",
      });
      isLoading.value = false; // 数据加载完成，隐藏加载提示
    });
};

// 单独购买商品
const placeOrder = (product) => {
  const selectedProducts = [
    {
      ...product,
      productName: product.productName,
      productPrice: product.productPrice,
    },
  ];
  console.log("传递给支付页面的商品数据：", selectedProducts); // 添加日志
  const apiResponse = {
    msg: "成功",
  };
  router.push({
    path: "payment",
    name: "Payment",
    query: {
      buyerid: buyerid,
      apiResponse: JSON.stringify(apiResponse),
      products: JSON.stringify(selectedProducts),
    },
  });
};

//批量购买
const batchOrder = () => {
  if (selectedCartIds.length === 0) {
    ElMessage({
      message: $t("shoppingcart.selectItemsMessage"),
      type: "warning",
    });
    return;
  }
  const selectedProducts = selectedCartIds
    .map((item) => {
      const product = shoppingCart.products.find(
        (p) => p.productId === item.productId
      );
      if (!product) {
        console.error("未找到对应的商品信息，productId:", item.productId);
      }
      return {
        ...product,
        productName: product.productName,
        productPrice: product.productPrice,
      };
    })
    .filter((product) => product); // 过滤掉未找到的商品;
  const apiResponse = {
    msg: "成功",
  };
  router.push({
    path: "payment",
    name: "Payment",
    query: {
      buyerid: buyerid,
      apiResponse: JSON.stringify(apiResponse),
      products: JSON.stringify(selectedProducts),
    },
  });
};

// 批量收藏
const batchCollect = () => {
  if (selectedCartIds.length === 0) {
    ElMessage({
      message: $t("shoppingcart.selectProductsMessage"),
      type: "warning",
    });
    return;
  }

  // 提取选中商品的 productId
  const productIds = selectedCartIds
    .map((item) => {
      const product = shoppingCart.products.find((p) => p.id === item.id);
      return product ? product.productId : null;
    })
    .filter((id) => id !== null);

  const requestData = {
    buyerId: buyerid,
    productId: productIds,
  };

  // 批量收藏逻辑
  request
    .post(`/collect/addCollectsBatch`, requestData)
    .then((res) => {
      if (res.msg === "成功") {
        ElMessage({
          message: $t("shoppingcart.batchCollectSuccessMessage"),
          type: "success",
        });
      }
    })
    .catch((err) => {
      console.error("批量转收藏失败：", err);
    });
};

//批量删除购物车商品
const batchDelete = () => {
  if (selectedCartIds.length === 0) {
    ElMessage({
      message: $t("shoppingcart.selectItemsMessage"),
      type: "warning",
    });
    return;
  }
  const ids = selectedCartIds.map((item) => item.id);
  console.log("要删除的商品 ID 数组:", ids); // 打印要删除的商品 ID 数组
  request
    .delete("/ShoppingCart/delShoppingCartBatch", { data: ids })
    .then((res) => {
      if (res.msg === "成功") {
        ElMessage({
          message: $t("shoppingcart.batchDeleteSuccessMessage"),
          type: "success",
        });
        getUserCartItems(); // 重新加载购物车数据
      } else {
        ElMessage({
          message: $t("shoppingcart.deleteErrorMessage"),
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("批量删除失败：", err);
      ElMessage({
        message: $t("shoppingcart.requestErrorMessage"),
        type: "error",
      });
    });
};

//删除单个商品
const deleteSingleProduct = (shoppingCartId) => {
  request
    .delete("/ShoppingCart/delShoppingCartBatch", { data: [shoppingCartId] })
    .then((res) => {
      if (res.msg === "成功") {
        ElMessage({
          message: $t("shoppingcart.deleteSuccessMessage"),
          type: "success",
        });
        getUserCartItems(); // 重新加载购物车数据
      } else {
        ElMessage({
          message: $t("shoppingcart.deleteErrorMessage"),
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.error("删除失败：", err);
      ElMessage({
        message: $t("shoppingcart.requestErrorMessage"),
        type: "error",
      });
    });
};

//获取商品的第一张图片
const getProductImage = (product) => {
  //如果商品有多张图片，返回第一张图片
  if (product.imagePath && product.imagePath.length > 0) {
    const imageFiles = product.imagePath.split(";");
    return imageFiles.length > 0 ? `${imageFiles[0]}` : ""; // 假设图片数组是 `images`
  }
  return "";
};

// 全选/反选功能
const handleCheckAll = (value) => {
  shoppingCart.products.forEach((product) => {
    product.checked = value;
  });
  updateSelectedCartIds(); // 更新已选购物车项
  console.log("全选/反选后已选的购物车项为：", selectedCartIds); // 打印已选购物车项
};

// 更新已选购物车项
const updateSelectedCartIds = () => {
  selectedCartIds.length = 0; // 清空当前已选购物车项
  shoppingCart.products.forEach((product) => {
    if (product.checked) {
      selectedCartIds.push({
        id: product.id,
        productId: product.productId,
        quantity: product.quantity,
      });
    }
  });
  console.log("已选购物车项（update）:", selectedCartIds); // 打印已选购物车项ID
  selectedCartIds.forEach(({ productId, id }) => {
    console.log("商品 ID:", productId, "购物车ID:", id); // 检查每个购物车的ID和商品ID
  });
};

// 计算商品总价
const calculateTotalPrice = (product) => {
  product.totalPrice = product.unitPrice * product.quantity;
};

// 搜索功能
const search = () => {
  const requestData = {
    name: data.name,
    select: data.select,
    buyerid: buyerid,
  };
  request
    .get("/Ai/abbreviation", { params: requestData })
    .then((res) => {
      if (res.data) {
        shoppingCart.products = res.data;
        shoppingCart.products.forEach((product) => {
          product.checked = false;
          calculateTotalPrice(product);
        });
      } else {
        shoppingCart.products = [];
        ElMessage({
          message: $t("shoppingcart.noSearchResultsMessage"),
          type: "warning",
        });
      }
    })
    .catch((err) => {
      console.error("搜索失败：", err);
      ElMessage({
        message: $t("shoppingcart.searchErrorMessage"),
        type: "error",
      });
    });
};

//页面加载时获取购物车数据
onMounted(() => {
  getUserCartItems();
  loadCategories();
});
</script>
